package com.jb.repair.acticity;

import android.content.Intent;
import android.content.SharedPreferences;
import android.media.audiofx.EnvironmentalReverb;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Looper;
import android.os.Message;
import android.provider.Settings;
import android.util.Log;
import android.view.View;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import com.RS.AndroidSDK.HardwareCtrl;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.jb.repair.F1Application;
import com.jb.repair.acticity.MainActivity;
import com.jb.repair.R;
import com.jb.repair.common.AppConfig;
import com.jb.repair.common.Constants;
import com.jb.repair.dao.Db;
import com.jb.repair.model.User4Json;
import com.jb.repair.net.HttpClient;
import com.jb.repair.util.MD5Util;
import com.jb.repair.util.MessageUtil;
import com.jb.repair.util.NetUtil;
import com.jb.repair.util.SharePreferenceUtil;
import com.jb.repair.util.StringUtils;
import com.jb.repair.view.TitleView;

import org.json.JSONObject;

import java.io.File;
import java.util.HashMap;
import java.util.Map;

public class LoginActivity extends BaseActivity {

    TitleView titleView;
    EditText tv_name, tv_pass;
    CheckBox ck_auto, ck_pass;
    TextView tv_login;
    Db db;
    SharePreferenceUtil sp;
    SharedPreferences sp2;

    String name, pass;

    private String TAG = "LoginActivity";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);
        sp2 = getSharedPreferences(Constants.SP_NAME, this.MODE_PRIVATE);
        //判断数据库是否存在
        File file = new File(AppConfig.DB_PATh);
        if (!file.exists()) {
            Log.e("Tag", "数据库不存在");
            sp2.edit().putString(Constants.PERSON_GUID, "").commit();
            sp2.edit().putString(Constants.PERSON_NAME, "").commit();
            sp2.edit().putString(Constants.PERSON_LOGO_ID, "").commit();
            Intent intent = new Intent(LoginActivity.this, ConfigActivity.class);
            startActivity(intent);
            finish();
        } else {
            Log.e("Tag", "数据库存在");
            sp = SharePreferenceUtil.getInstance(this, "pass.txt");
            db = Db.getInstance(this);
            initviews();
        }
    }


    private void initviews() {
        titleView = (TitleView) findViewById(R.id.titleView);
        tv_name = (EditText) findViewById(R.id.tv_name);
        tv_pass = (EditText) findViewById(R.id.tv_pass);
        ck_auto = (CheckBox) findViewById(R.id.ck_auto);
        ck_pass = (CheckBox) findViewById(R.id.ck_pass);
        tv_login = (TextView) findViewById(R.id.tv_login);

        String name1 = sp.getString("name", "");
        tv_name.setText(name1);

        boolean ck_pass1 = sp.getBoolean("ck_pass", false);
        boolean ck_auto1 = sp.getBoolean("ck_auto", false);
        if (ck_pass1) {
            ck_pass.setChecked(true);
            String pass1 = sp.getString("pass", "");
            tv_pass.setText(pass1);

            if (ck_auto1) {
                ck_auto.setChecked(true);
                login();
            }
        }


        tv_login.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {

                login();

            }
        });

        titleView.setOnClickListener(new TitleView.OnTitleViewClickListener() {
            @Override
            public void onRightImage1Click(View view) {
                super.onRightImage1Click(view);
                Intent intent = new Intent(LoginActivity.this, ConfigActivity.class);
                startActivity(intent);
            }
        });
    }

    private class LoginTask extends AsyncTask<String, Void, String> {
        @Override
        protected String doInBackground(String... params) {
            Log.i(TAG, "baseurl = " + AppConfig.BASE_URL);
            String url = AppConfig.BASE_URL + Constants.LOGIN_URL;
            Log.i(TAG, "在线登陆URL：" + url);
            String result = "";
            Map<String, String> map = new HashMap<>();
            map.put("username", params[0]);
            map.put("password", params[1]);
            map.put("pageStyle", "");
            map.put("logined", params[0]);
            map.put("agent", "1");
            result = new HttpClient(getApplicationContext()).doPost(url, map);
            Log.i(TAG, "登陆返回结果：" + result);
            return result;
        }

        @Override
        protected void onPostExecute(String s) {
            super.onPostExecute(s);
            MessageUtil.dismissProgressDialog();
            Gson gson = new Gson();
            try {
                JSONObject jsonObject = new JSONObject(s);
                String successful = jsonObject.getString("successful");
                if ("false".equals(successful)) {
                    MessageUtil.dismissProgressDialog();
                    MessageUtil.showToast(getApplicationContext(), "用户名或密码错误");
                    return;
                }
                User4Json uj = gson.fromJson(s, new TypeToken<User4Json>() {
                }.getType());
                if (uj.successful.equals("true")) {
                    MessageUtil.showToast(getApplicationContext(), "在线登陆成功");
                    sp2.edit().putString(Constants.PERSON_GUID, uj.resultValue.persGuid).commit();
                    sp2.edit().putString(Constants.PERSON_NAME, uj.resultValue.persName).commit();
                    sp2.edit().putString(Constants.PERSON_LOGO_ID, name).commit();
                    F1Application.setUserName(uj.resultValue.persName);
                    Log.i(TAG, "uj.resultValue.persGuid = " + uj.resultValue.persGuid);
                    F1Application.setUserId(uj.resultValue.persGuid);
                    Log.i(TAG, "F1Application.getUserId() = " + F1Application.getUserId());
                    //跳转页面
                    setLogin();
                }
            } catch (Exception e) {
                MessageUtil.dismissProgressDialog();
                MessageUtil.showToast(getApplicationContext(), "网络异常");
            }
        }
    }

    private void login() {
        MessageUtil.showProgressDialog(LoginActivity.this, "正在登陆");
        name = tv_name.getText().toString();
        pass = tv_pass.getText().toString();
        if (StringUtils.isNullOrEmpty(name) || StringUtils.isNullOrEmpty(pass)) {
            Toast.makeText(LoginActivity.this, "用户名和密码不能为空", Toast.LENGTH_SHORT).show();
            MessageUtil.dismissProgressDialog();
        } else if (NetUtil.isNetOK(getApplicationContext())) { //联网状态下进行在线登陆
            Log.i(TAG, "在线登陆");
            String md5_pass = MD5Util.parse(pass);
            Log.i(TAG, md5_pass);
            new LoginTask().execute(name, md5_pass);
        } else {
            Log.i(TAG, "离线登陆");
            String md5_pass = MD5Util.parse(pass);
            Log.e("Tag", md5_pass);
            String db_pass = db.getName("LOGO_PASS", "TB_SYS_PERSON", "LOGO_ID", name);
            Log.e("Tag---", db_pass + "haha");
            if (db_pass == null || db_pass.equals("")) {
                name = name.toLowerCase();
                db_pass = db.getName("LOGO_PASS", "TB_SYS_PERSON", "LOGO_ID", name);

            }
            Log.e("Tag---", db_pass + "haha");

            if (ck_auto.isChecked() && !ck_pass.isChecked()) {
                Toast.makeText(LoginActivity.this, "自动登录需要记住密码", Toast.LENGTH_SHORT).show();
                return;
            }

            if (md5_pass.equals(db_pass)) {
                Toast.makeText(LoginActivity.this, "登录成功", Toast.LENGTH_SHORT).show();
                //判断是否需要数据同步
                // invokeInterfaceDemo();
                //取出该账号对应的人员GUID和人员姓名
                String[] person = db.getPersonNameById(name);
                sp2.edit().putString(Constants.PERSON_GUID, person[0]).commit();
                sp2.edit().putString(Constants.PERSON_NAME, person[1]).commit();
                sp2.edit().putString(Constants.PERSON_LOGO_ID, name).commit();
                F1Application.setUserName(person[1]);
                F1Application.setUserId(person[0]);
                Log.i("tag", name);
                //跳转页面
                setLogin();

            } else {
                Toast.makeText(LoginActivity.this, "用户名或密码错误", Toast.LENGTH_SHORT).show();
            }
            MessageUtil.dismissProgressDialog();
        }
    }

    private void setLogin() {
        Log.i(TAG,"enter setLogin...");
        sp.setString("name", name);
        if (ck_pass.isChecked()) {
            sp.setBoolean("ck_pass", true);
            sp.setString("pass", pass);
            if (ck_auto.isChecked()) {
                sp.setBoolean("ck_auto", true);
            } else {
                sp.setBoolean("ck_auto", false);
            }
        } else {
            sp.setBoolean("ck_pass", false);
        }
        Log.i(TAG,"startActivity...");
        Intent intent = new Intent(LoginActivity.this, MainActivity.class);

        startActivity(intent);
    }

}
